//
//  EncodableEx.swift
//
//  Created by LL on 2024/6/25.
//

import Foundation

extension Encodable {
    var toData: Data? {
        return try? JSONEncoder().encode(self)
    }

    var toJsonString: String? {
        guard let data = toData else { return nil }
        return String(bytes: data, encoding: .utf8)
    }

    var toDictionary: [String: Any] {
        guard let data = toData,
              let dict = try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: Any]
        else { return [:] }

        return dict
    }
}
